package com.seeyoui.kensite.framework.file.service;

import com.seeyoui.kensite.framework.file.converter.OfficeDocumentConverter;
import com.seeyoui.kensite.framework.file.converter.office.DefaultOfficeManagerConfiguration;
import com.seeyoui.kensite.framework.file.converter.office.OfficeManager;
import com.seeyoui.kensite.framework.file.extend.ControlDocumentFormatRegistry;
import com.sun.star.document.UpdateDocMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.PropertyResourceBundle;

/**
 * 创建文件转换器
 *
 * @author yudian-it
 * @date 2017/11/13
 */
@Service
public class Converter {
    @Autowired
    static private OfficeManager officeManager;
    PropertyResourceBundle prb = (PropertyResourceBundle) PropertyResourceBundle.getBundle("file-management");
    String officeHome = prb.getString("office.home");
    @PostConstruct
    public void initOfficeManager() {
        /*DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
        configuration.setOfficeHome(officeHome);
        configuration.setPortNumber(8100);
        officeManager = configuration.buildOfficeManager();
        officeManager.start();*/
    }

    public static OfficeDocumentConverter getDocumentConverter() {
        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager, new ControlDocumentFormatRegistry());
        converter.setDefaultLoadProperties(getLoadProperties());
        return converter;
    }

    private static Map<String,?> getLoadProperties() {
        Map<String,Object> loadProperties = new HashMap<>(10);
        loadProperties.put("Hidden", true);
        loadProperties.put("ReadOnly", true);
        loadProperties.put("UpdateDocMode", UpdateDocMode.QUIET_UPDATE);
        loadProperties.put("CharacterSet", Charset.forName("UTF-8").name());
        return loadProperties;
    }

    @PreDestroy
    public void destroyOfficeManager(){
        if (null != officeManager && officeManager.isRunning()) {
            officeManager.stop();
        }
    }

}
